package com.spark.data

import android.content.DialogInterface
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v4.app.DialogFragment
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.spark.colliery.common.ext.gone
import com.spark.colliery.common.ext.watchWithClear
import com.spark.common.ext.color
import com.spark.common.ext.colorWithUnderline
import com.spark.common.ext.sdf
import com.spark.common.ext.setBackgroundAlpha
import com.spark.common.helper.DatePickerDiaFragment
import com.spark.common.helper.SpacesItemDecoration
import kotlinx.android.synthetic.main.dal_data_qr_category.*

/**
 * Category Search
 */
class DataQrFilterFragment : DialogFragment() {
    private var onSearchActionListener: OnSearchActionListener? = null
    /**
     * to result to be transported
     */
    private var result = SideTargetSearchModel()

    companion object {
        fun newInstance(): NotifyHistoryFilterFragment {
            val fragment = NotifyHistoryFilterFragment()
            val args = Bundle()

            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFragmentAnimStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.dal_data_qr_category, container)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        /**
         * touch to dismiss
         */
        val window = dialog.window
        window.decorView.setOnTouchListener { v, event ->
            dismiss()
            return@setOnTouchListener true
        }
        /**
         * mannual set the width of layout
         */
        val screenWidth = resources.displayMetrics.widthPixels
        val lp = window.attributes

        lp.width = screenWidth * 3 / 5
        lp.gravity = Gravity.RIGHT
        window.attributes = lp
        /**
         * the authority of user can filter it
         */
        tv_authority_file.apply {
            text = "授权文件".colorWithUnderline(resources.getColor(R.color.color0092dfblue))
            setOnClickListener {
                text = "授权文件".colorWithUnderline(resources.getColor(R.color.color0092dfblue))
                tv_whole_file.text = "全部文件".color(resources.getColor(R.color.color666), 0, 4)
                result.scopendContentId = "1"
            }
        }
        tv_whole_file.apply {
            text = "全部文件".color(resources.getColor(R.color.color666), 0, 4)
            setOnClickListener {
                text = "全部文件".colorWithUnderline(resources.getColor(R.color.color0092dfblue))
                tv_authority_file.text = "授权文件".color(resources.getColor(R.color.color666), 0, 4)
                result.scopendContentId = "2"
            }
        }
        /**
         * search frame
         */
        val ivClear = view.findViewById<ImageView>(R.id.iv_clear)
        val etSearch = view.findViewById<EditText>(R.id.et_earch)
        etSearch.watchWithClear(ivClear)
        ivClear.setOnClickListener { etSearch.setText("") }
        /**
         * start time
         */
        tv_start_time.setOnClickListener {
            val datePickerDialog = DatePickerDiaFragment.newInstance()
            datePickerDialog.show(childFragmentManager, "DatePicker")
            datePickerDialog.setOnDateTapedListener {
                tv_start.gone(false)
                tv_and.gone(false)
                ll_time_result.gone(false)
                tv_start.text = sdf("yy.MM.dd").format(it)
            }
        }
        /**
         * end time
         */
        tv_end_time.setOnClickListener {
            val datePickerDialog = DatePickerDiaFragment.newInstance()
            datePickerDialog.show(childFragmentManager, "DatePicker")
            datePickerDialog.setOnDateTapedListener {
                tv_end.gone(false)
                tv_start.text = sdf("yy.MM.dd").format(it)
            }
        }
        /**
         * tag
         */
        val recyTags = view.findViewById<RecyclerView>(R.id.recy_tags)
        val tagAdapter = TagAdapter(R.layout.item_dal_data_qr_cate)
        recyTags.adapter = tagAdapter
        recyTags.layoutManager = object : GridLayoutManager(context, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }

            override fun canScrollHorizontally(): Boolean {
                return false
            }
        }
        recyTags.addItemDecoration(SpacesItemDecoration(2, 0, 0, 10, resources.getColor(R.color.color666)))

        val tags = mutableListOf(
                Tag("防爆", false),
                Tag("气流", false),
                Tag("井下", false),
                Tag("安全", false),
                Tag("消防", false),
                Tag("运输", false),
                Tag("防爆", false),
                Tag("气流", false),
                Tag("井下", false),
                Tag("安全", false),
                Tag("消防", false),
                Tag("运输", false)
        )
        tagAdapter.addData(tags)

        tagAdapter.setOnItemClickListener { adapter, view, position ->
            tagAdapter.data.forEachIndexed { index, tag ->
                tag.isSelected = index == position
            }
            tagAdapter.notifyDataSetChanged()
        }

        val tvReset = view.findViewById<TextView>(R.id.tv_reset)
        val tvSearch = view.findViewById<TextView>(R.id.tv_search)
        /**
         * reset
         */
        tvReset.setOnClickListener {
            tv_authority_file.apply {
                text = "授权文件"
                setTextColor(resources.getColor(R.color.color666))
            }
            tv_whole_file.apply {
                text = "全部文件"
                setTextColor(resources.getColor(R.color.color666))
            }
            etSearch.setText("")
            tv_start.gone(true)
            tv_and.gone(true)
            tv_end.gone(true)
            tagAdapter.data.forEach {
                it.isSelected = false
            }
            tagAdapter.notifyDataSetChanged()
        }
        /**
         * goSearch
         */
        tvSearch.setOnClickListener {
            result.keyword = etSearch.text.toString().trim()
            result.startTime = tv_start.text.toString()
            result.endTime = tv_end.text.toString()
            tagAdapter.data.forEach {
                if (it.isSelected)
                    result.brands = it.tag
            }
            onSearchActionListener?.onSearch(result)
        }
    }

    override fun onResume() {
        super.onResume()
        activity?.apply { window.setBackgroundAlpha(0.6F) }
    }

    override fun onDismiss(dialog: DialogInterface?) {
        super.onDismiss(dialog)
        activity?.apply { window.setBackgroundAlpha(1.0F) }
    }

    fun addSearchActionListener(listener: (SideTargetSearchModel) -> Unit) {
        onSearchActionListener = object : OnSearchActionListener {
            override fun onSearch(result: SideTargetSearchModel) {
                listener(result)
            }

        }
    }

    /**
     * The interface notify to search
     */
    interface OnSearchActionListener {
        fun onSearch(result: SideTargetSearchModel)
    }

    /**
     * Tag adapter
     */
    class TagAdapter(@LayoutRes layoutRes: Int) : BaseQuickAdapter<Tag, BaseViewHolder>(layoutRes) {
        override fun convert(helper: BaseViewHolder?, item: Tag?) {
            if (item == null) return
            helper?.apply {
                setText(R.id.tv_tag, item.tag)
                val color = if (item.isSelected) mContext.resources.getColor(R.color.color0092dfblue) else mContext.resources.getColor(R.color.color666)
                setTextColor(R.id.tv_tag, color)
            }
        }
    }

    data class Tag(
            var tag: String = "",
            var isSelected: Boolean = false
    )
}

/**
 * the target keywords to require filter the search result
 */
data class SideTargetSearchModel(
        var scopendContentId: String = "",
        var keyword: String = "",
        var brands: String = "",
        var startTime: String = "",
        var endTime: String = "")